let formSelects;
let baseUrl;
layui.define(['index', 'form', 'zmnApp', 'table', 'laypage', 'layedit', 'laydate', 'formSelects', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laydate = layui.laydate;
    let zmnApp = layui.zmnApp;
    var zmnSelect = layui.zmnSelect;
    formSelects = layui.formSelects;
    baseUrl = zmnApp.SYS_BASE_URL;

    zmnSelect.searchStaff('staffId', {
        searchedValue: json.vo.staffSearchValue,
        selectedValues: json.vo.staffId,
        isRadio: true,
        remote: {
            limitPermit: json.vo.staffName,
            events: {
                extendParams: function () {
                    return {
                        status: null,
                    }
                }
            }
        },
        events: {
            changed: function (values) {
                console.log("========staffId=========")
                console.log("已选中的值:" + values)
            }
        }
    });

    $('#staffIds .xm-search-input').on('input propertychange', function () {
        json.vo.staffSearchValue = $('#staffId .xm-search-input').val();
    });

    var cols = [
        [
            {field: 'staffId', type: 'numbers', title: '序号', align: 'center', fixed: 'left'},
            {field: 'staffId', title: '员工ID', width: 80, align: 'center'},
            {field: 'realName', title: '姓名', width: 100, align: 'center'},
            {field: 'companyName', title: '公司', width: 120, align: 'center'},
            {
                field: 'plat', title: '平台', width: 80, align: 'center', templet: function (d) {
                    return translatePlatName(d.plat);
                }
            },
            {field: 'deptName', title: '部门', align: 'center'},
            {field: 'uri', title: 'URI', align: 'center'},
            {field: 'app', title: 'APP', align: 'center'},
            {field: 'ip', title: 'IP', align: 'center'},
            {
                field: 'province', title: '省', width: 80, align: 'center', templet: function (d) {
                    if (d.ipInfoVo == null || d.ipInfoVo.province == null) {
                        return '';
                    }
                    return d.ipInfoVo.province;
                }
            },

            {
                field: 'city', title: '市', width: 80, align: 'center', templet: function (d) {
                    if (d.ipInfoVo == null || d.ipInfoVo.city == null) {
                        return '';
                    }
                    return d.ipInfoVo.city;
                }
            },
            {field: 'method', title: '请求方式', width: 70, align: 'center'},
            {
                field: 'time', title: '操作时间', align: 'center', templet: function (row) {
                    return zmnUtil.createTime(row.time);
                }
            },
            {
                fixed: 'right', title: '操作', width: 175, align: 'center', templet:function (d) {
                  return  '<div><a href="#" onclick="toDetail(\'' + d._id + '\')" class="layui-btn layui-btn-xs"><i class="layui-icon">&#xe642;</i>详情</a></div>'
                }
            }
        ]
    ];


    form.on('submit(query-submit)', function (obj) {

        if (obj.field.staffId == null || obj.field.staffId == '') {
            layer.alert("请选择员工");
            return false;
        }

        let timeRange = $("#timeRange").val();
        let times = timeRange.split(' - ');
        obj.field.startTime = times[0];
        obj.field.endTime = times[1];
        if (obj.field.startTime > obj.field.endTime) {
            layer.msg("开始时间不能大于结束时间");
            return false;
        }
        tableRender(obj.field);
        return false;
    });

    let tableRender = function (data) {
        table.render({
            id: "zmn-staff-log-table"
            , url: "/staff/log/loadData.action"
            , where: data
            , cols: cols
            , elem: "#zmn-staff-log-table"
            , toolbar: "#zmn-staff-log-table-tool"
            , defaultToolbar: ['filter'] // ['filter', 'print', 'exports']
            , loading: true
            , page: {
                prev: "上一页"
                , next: "下一页"
                , hash: true
                , limit: 50
                , limits: [10, 50, 100]
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit       //?curr=1&nums=30
            }
            , response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                , statusCode: 200 //规定成功的状态码，默认：0
            }
        });
    };

    tableRender(null);
    initSelect(zmnApp);

    laydate.render({
        elem: '#timeRange',
        range: true
    });

    // 2级部门联动
    form.on('select(deptOneId)', function (obj) {
        triggerTwoDeptOptions(obj.value);
    });

    function triggerTwoDeptOptions(value) {
        let twoDeptOptions = json.twoDepts.filter(p => p.parentId == value).map(p => {
            return p.deptId == json.vo.deptTwoId ? '<option value="' + p.deptId + '" selected="selected">' + p.deptName + '</option>' : '<option value="' + p.deptId + '">' + p.deptName + '</option>';
        });
        twoDeptOptions.unshift('<option value=""></option>');
        $('#deptTwoId').html(twoDeptOptions);
        form.render("select");
    }

    function translatePlatName(plat) {
        if (plat == 10) {
            return "啄木鸟";
        }
        if (plat == 20) {
            return "言而有信";
        }
        if (plat == 30) {
            return "一步维修";
        }
        if (plat == 40) {
            return "川南维保";
        }
        return "-";
    }

    exports('staff_log_list', {});
});

function initSelect(zmnApp) {
    formSelects.config('departId', {
        keyName: 'value',
        keyVal: 'key',
        keyChildren: 'list',
        success: function (id, url, val, result) {
            formSelects.value('departId', []);
        },
        error: function (id, url, val, err) {
            console.log(id + ":" + err);
        }
    });

    /**
     * 1.多选数据赋值
     *
     * formSelects.data(ID, type, config);
     *
     * @param ID            xm-select的值
     * @param type          'local' | 'server', 本地数据或者远程数据
     * @param config        配置项
     *          arr             本地数据数组
     *          url             远程数据链接
     *          keyword         远程数据搜索内容, 其他附加数据可以使用 formSelects.config设置
     *          linkage         是否为联动多选（就是把上级地扯关联一起显示/选择，true时必须全择到最底层一条线才行）
     *          linkageWidth    联动多选没级宽度
     */
    formSelects.data('departId', 'server', {
        url: zmnApp.SYS_BASE_URL + '/channel/loadZmnCompanyDept.action',
        linkage: false,
        linkageWidth: 130
    });
}

function toDetail(id) {
    layer.open({
        type: 2,
        title:'详情',
        area: ['1200px', '600px'],
        content: baseUrl + '/staff/log/detail.action?id='+id
    });
}